import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import {ApiResponse} from "../ts/CommonTypes";


// 创建 Axios 实例
const request: AxiosInstance = axios.create({
  // api 的 base_url
  baseURL:
      import.meta.env.MODE === 'development'
          ? ''
          : (import.meta.env.VITE_API_DOMAIN as string),
  timeout: 60000,
})

// 请求拦截器
request.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      const token = localStorage.getItem('Authorization')
      if (token) {
        config.headers = config.headers || {}
        config.headers.Authorization = token
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    (res: AxiosResponse<ApiResponse>) => {
      // 处理无权限的情况
      if (res.status === 401) {
        localStorage.removeItem('Authorization')
        window.location.href = '/login'
      }

      // 登录失效 code=10000
      if (res.status === 200) {
        if (res.data.code === 10000) {
          localStorage.removeItem('Authorization')
          window.location.href = '/login'
        } else {
          return Promise.resolve(res.data)
        }
      } else {
        return Promise.reject(res.statusText)
      }
    },
    (error) => {
      return Promise.reject(error)
    }
)

export default request
